<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <a-row :gutter="16">
        <a-col :span="8">
<!--          <a-button type="primary" @click="add">insert</a-button>-->
          <a-table  :row-key="record=>record.id" :columns="columns" :data-source="level" :pagination="false">
            <template #bodyCell="{ column ,record}">
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button type="primary" @click="update(record)">
                    <template #icon><edit-outlined /></template>
                  </a-button>
                  <a-popconfirm
                      title="Are you sure delete this record?"
                      ok-text="Yes"
                      cancel-text="No"
                      @confirm="confirmDel(record.id)"
                      @cancel="cancel"
                  >
                    <a-button type="primary" danger >
                      <template #icon><delete-outlined /></template>
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
        </a-table>
        </a-col>
        <a-col :span="16">
          <a-space style="padding-bottom: 10px">
            <a-button type="primary" @click="handleOk">OK</a-button>
            <a-button type="primary" @click="setVisible">Document Preview</a-button>
          </a-space>
          <a-form :model="formState" >
            <a-form-item>
              <a-input v-model:value="formState.name" placeholder="Doc Name"/>
            </a-form-item>
            <a-form-item>
              <a-tree-select
                  v-model:value="formState.parent"
                  show-search
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="Doc Parent"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="treeData"
                  :field-names="{
                      children: 'children',
                      label: 'name',
                      value: 'id',
                    }"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model:value="formState.sort" placeholder="Doc Sort"/>
            </a-form-item>
            <a-form-item>
              <div style="border: 1px solid #ccc">
                <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                />
                <Editor
                    style="height: 500px; overflow-y: hidden;"
                    v-model="valueHtml"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                />
              </div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-layout-content>

    <a-drawer
        v-model:visible="visible"
        class="custom-class"
        title="文档预览"
        width="900px"
        placement="right">
      <div class="wangeditor" :innerHTML = valueHtml></div>
    </a-drawer>

  </a-layout>
</template>

<script>
import{EditOutlined, DeleteOutlined} from '@ant-design/icons-vue';
import axios from "axios";
import {onBeforeUnmount,ref,shallowRef,onMounted } from "vue"
import { message } from 'ant-design-vue'
import {arrayToTree,isEmpty} from "@/util/Tool";
import {useRoute} from "vue-router";
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar,} from '@wangeditor/editor-for-vue'

export default {
  name: "AdminDoc",
  components: { Editor, Toolbar,EditOutlined,DeleteOutlined},
  setup(){

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('')

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const rou = useRoute()
    const columns  = ref([
      {
        title: 'name',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: 'action',
        dataIndex: 'action',
        key: 'action',
      },
    ])
    const level = ref();
    const visible = ref(false);
    const formState = ref({})


    onMounted(()=>{
      console.log("onMounted AdminDoc")
      load()
    })

    function load() {
      console.log("load...")

      axios.get("api/docList/"+rou.query.ebookId,)
        .then(res => {
          console.log(res)
          if(res.data.code === "200"){
            // doc.value = res.data.data
            level.value = arrayToTree(res.data.data,0)
            formState.value = {
              ebookId:rou.query.ebookId
            }
            treeData.value = JSON.parse(JSON.stringify(level.value))
            setDisabled(treeData.value,0)
            treeData.value.unshift({id:0,name:'无'})
          }else{
            message.error(res.data.msg);
          }
        })
    }

    const treeData = ref()

    const setDisabled = (data,id) =>{
      for(let i=0;i<data.length;i++){
        const d = data[i];
        if(d.id === id){
          d.disabled = true

        //  遍历子文档
          const child = d.children
          if(!isEmpty(child)){
              for(let j =0;j<child.length;j++){
                setDisabled(child,child[j].id)
              }
          }
        }else{
          const child = d.children
          if(!isEmpty(child)){
            setDisabled(child,id)
          }
        }
      }
    }

    const update = (record) => {
      console.log("update")
      valueHtml.value=''
      axios.get('api/docContent/'+record.id)
        .then(res => {
          valueHtml.value = res.data.data
          message.success(res.data.msg);
        })

      formState.value = JSON.parse(JSON.stringify(record))
      treeData.value = JSON.parse(JSON.stringify(level.value))
      setDisabled(treeData.value,record.id)
      treeData.value.unshift({id:0,name:'无'})
    };

    const add = () => {
      valueHtml.value=''
      formState.value = {
        ebookId:rou.query.ebookId
      }
      treeData.value = JSON.parse(JSON.stringify(level.value))
      treeData.value.unshift({id:0,name:'无'})
    };

    const handleOk = () => {
      console.log("handleOk")
      formState.value.content = valueHtml.value

      axios.post("api/doc",formState.value)
          .then(res => {
            console.log(res.data.code)
            if(res.data.code === "200"){
              message.success(res.data.msg);
              load()
              valueHtml.value=''
              formState.value = {
                ebookId:rou.query.ebookId
              }
            }else{
              message.error(res.data.msg);
            }
          })
    }

    const deleteIds = []

    const setDeleteIds = (data,id) =>{
      for(let i=0;i<data.length;i++){
        const d = data[i];
        if(d.id === id){
          deleteIds.push(id)

          //  遍历子文档
          const child = d.children
          if(!isEmpty(child)){
            for(let j =0;j<child.length;j++){
              setDeleteIds(child,child[j].id)
            }
          }
        }else{
          const child = d.children
          if(!isEmpty(child)){
            setDeleteIds(child,id)
          }
        }
      }
    }

    const confirmDel = (id) => {
      console.log("confirmDel")
      treeData.value = JSON.parse(JSON.stringify(level.value))
      setDeleteIds(treeData.value,id)
      console.log(deleteIds.join(","))
      axios.delete("api/doc/"+deleteIds.join(","),)
          .then(res => {
            console.log(res.data.code)
            if(res.data.code === "200"){
              message.success(res.data.msg);
              load()
            }else{
              message.error(res.data.msg);
            }
          })
    };

    const setVisible=()=>{
      visible.value = true
    }
    return{
      columns,
      level,
      visible,
      formState,
      treeData,
      update,
      add,
      handleOk,
      setDeleteIds,
      confirmDel,
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      setVisible
    }
  }
}
</script>

<style>
/* table 样式 */
.wangeditor table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
.wangeditor  table td,
.wangeditor table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
}
.wangeditor table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
}

/* blockquote 样式 */
.wangeditor blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
.wangeditor code {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
.wangeditor pre code {
  display: block;
}

/* ul ol 样式 */
.wangeditor ul, ol {
  margin: 10px 0 10px 20px;
}
</style>